/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 /***************************************************************************
 * Name: uds_transport.c
 *
 * Purpose: implementation implementation unix domain socket transport(dialer and listener) ops for cbus
 *
 * Developer:
 *   wen.gu , 2022-02-16
 *
 * TODO:
 *
 ***************************************************************************/

 /******************************************************************************
 **    INCLUDES
 ******************************************************************************/

#ifdef LINUX_ENABLE_TRANSPORT_IPC
#include "uds_transport.h"
#include <time.h>
#include <stddef.h>
//#include <process.h>

#include "cbus/core/cbus_worker.h"
#include "cbus/core/cbus_thread.h"

#include "cbus/core/cbus_log.h"
/******************************************************************************
 **    MACROS
 ******************************************************************************/
#define DIALER_RECEIVE_BUF_SIZE (1024 * 16)
#define DIALER_RECEIVE_SELECT_TIME_OUT_SEC 2
#define DIALER_CONNECT_SELECT_TIME_OUT_SEC 2
/******************************************************************************
 **    VARIABLE DEFINITIONS
 ******************************************************************************/

/******************************************************************************
 **    inner FUNCTION DEFINITIONS
 ******************************************************************************/

static GErrc dialer_create_socket(socket_t* socket_id, const GSTR url)
{
    socket_t socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);

    if (socket_fd < 0)
    {
        LOGE("create uds socket instance failed(%s)\n", strerror(errno));
        return G_ErrInsufficientResources;
    } 

    struct sockaddr_un client_addr;
    memset(&client_addr, 0, sizeof(client_addr));            /* fill socket address structure with our address */
    client_addr.sun_family = AF_UNIX;
    time_t timeTotal = time(NULL);
    struct tm* ptm = localtime(&timeTotal);
    snprintf(client_addr.sun_path, sizeof(client_addr.sun_path), "%s_client_%d_%d-%d-%d-%d.%d.%d_%d", 
        url, getpid(), ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec, socket_fd);

    LOGI("client addr:%s, len:%zd, spcket: %d\n", client_addr.sun_path, sizeof(struct sockaddr_un), socket_fd);
    int len = offsetof(struct sockaddr_un, sun_path) + strlen(client_addr.sun_path);
    int32_t ret = bind(socket_fd, (struct sockaddr*) & client_addr, len);
    if (ret < 0)
    {
        LOGE("bind client socket:%s, failed:%s\n", client_addr.sun_path, strerror(errno));
        close(socket_fd);
        socket_fd = INVALID_SOCKET;
        return G_ErrUndefined;
    }

    // set the socket in non-blocking
    unsigned long mode = 1;
    int result = ioctl (socket_fd, FIONBIO, &mode);
    if (result != NO_ERROR)
    {
        LOGE("ioctl failed with error: %d, %s\n", result, strerror(errno));
        close(socket_fd);
        socket_fd = INVALID_SOCKET;
        return G_ErrUndefined;
    }
    *socket_id = socket_fd;
    return G_OK;
}

static GErrc dialer_do_connect(socket_t socket_id, const GSTR url, GU32 timeout_ms)
{
    struct sockaddr_un server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sun_family = AF_UNIX;
    snprintf(server_addr.sun_path, sizeof(server_addr.sun_path), "%s", url);
    LOGI("client addr:%s, len:%zd\n", server_addr.sun_path, sizeof(struct sockaddr_un));
    GU32 try_count = 0;
    while (try_count++ < MAX_TRY_CONNECT_COUNT)
    {
        int res = connect(socket_id, (struct sockaddr*) & server_addr, sizeof(struct sockaddr_un));

        if (res == 0)
        {/** indicat connect to service success */
            return G_OK;
        }
        else if (res == -1) 
        {
            if (errno == EINTR)
            {
                continue; /** interruptted, just try again */
            }
            else if ((errno == EINPROGRESS) || (errno == EWOULDBLOCK))
            {
                /** connectting ,so break to 'select' flow */
                break;
            }
            else /** rellay error */
            {
                LOGE("[%s.%d]===>: connect to(%s) failed(err: %s)\n", __FUNCTION__, __LINE__, server_addr.sun_path, strerror(errno));
                return G_ErrUndefined;            
            }
        }        
    }

    fd_set write_set, Err;
    FD_ZERO(&write_set);
    FD_ZERO(&Err);
    FD_SET(socket_id, &write_set);
    FD_SET(socket_id, &Err);
    int32_t ret;

    if (timeout_ms == CBUS_TRANSPORT_CONNECT_WAIT_FOREVER)
    {
        ret = select(0, NULL, &write_set, &Err, NULL);
    }
    else
    {
        struct timeval time_val = { 0 };
        time_val.tv_sec = timeout_ms / 1000; /** default 2 second ,todo refine me?? */
        time_val.tv_usec = (timeout_ms % 1000) * 1000;     
        ret = select(0, NULL, &write_set, &Err, &time_val);
    }


    // check if the socket is ready
    
    //LOGD("[%s.%d]===>: ret: %d\n", __FUNCTION__, __LINE__, ret);
    if (ret > 0)
    {      
        return G_OK;
    }
    else if (ret == 0)
    {
        /** todo something */  
        return G_ErrTimeout;
    }
    else
    {
        LOGE("connect failed with error: %s\n", strerror(errno));
        return G_ErrUndefined;
    }    
}

/******************************************************************************
 **    FUNCTION DEFINITIONS
 ******************************************************************************/
/**
 * @brief create and initialize a dialer instance
 * @param handle [out] a instance of dialer
 * @return GErrc, success: G_OK, else error code.
 * 
*/
GErrc uds_dialer_initialize(GPHD* handle)
{
    if (!handle)
    {
        return G_ErrBadParameter;
    }

    *handle = (GPHD)"dialer";

    return G_OK;
}

/**
 * @brief destroy a dialer instance
 * @param handle [in] a instance of dialer
 * @return GErrc, success: G_OK, else error code.
 * 
 */
GErrc uds_dialer_finish(GPHD handle)
{
    if (!handle)
    {
        return G_ErrBadParameter;
    }

    //do nothing 
    return G_OK;
}

/**
 * @brief connect to a listener(service)
 * @param handle [in] a instance of dialer
 * @param url [in] the url adress of listener(service)
 * @return GErrc, success: G_OK, else error code.
 * 
 */
GErrc uds_dialer_connect(GPHD handle, const GSTR url, GU32 timeout_ms, GPHD* pipe_handle)
{
    if (!handle || !url || (strlen(url) <= UDS_TRANSPORT_URL_PREFIX_LEN)) /** url len must > UDS_TRANSPORT_URL_PREFIX_LEN */
    {
        return G_ErrBadParameter;
    }
    
    socket_t socket_id = INVALID_SOCKET;

    GErrc ret = dialer_create_socket(&socket_id, url + UDS_TRANSPORT_URL_PREFIX_LEN);

    if (ret == G_OK)
    {
        ret = dialer_do_connect(socket_id, url + UDS_TRANSPORT_URL_PREFIX_LEN, timeout_ms);

        if (G_OK == ret)
        {
            *pipe_handle = (GPHD)socket_id;
        }
    }

    return ret;
}

#endif /** end of LINUX_ENABLE_TRANSPORT_IPC */